import tkinter as tk
from tkinter import ttk, filedialog, messagebox
from data_processor import load_excel_data
from bid_algorithm import adjust_bids_periodically
from logger import log_message
import threading


class AutoBidApp:
    def __init__(self, root):
        self.root = root
        self.root.title("自动调价工具")
        self.root.geometry("800x600")
        self.root.configure(bg='#f5f5f5')  # Light gray background

        # Set window icon (optional)
        try:
            self.root.iconbitmap('icon.ico')  # Replace with your icon file
        except:
            pass

        self.stop_event = None
        self.adjustment_thread = None

        self.create_widgets()
        self._center_window()  # 居中显示窗口
        self.root.protocol("WM_DELETE_WINDOW", self.on_close)

    def _center_window(self):
        self.root.update_idletasks()
        width = self.root.winfo_width()
        height = self.root.winfo_height()
        x = (self.root.winfo_screenwidth() // 2) - (width // 2)
        y = (self.root.winfo_screenheight() // 2) - (height // 2)
        self.root.geometry(f'{width}x{height}+{x}+{y}')

    def on_close(self):
        if messagebox.askokcancel("退出", "程序正在运行, 确定要退出程序吗？"):
            if self.stop_event:
                self.stop_event.set()
            self.root.destroy()

    def create_widgets(self):
        # ===== Style Configuration =====
        style = ttk.Style()
        style.theme_use('clam')  # Modern theme

        # Configure styles
        style.configure('TFrame', background='#f5f5f5')
        style.configure('TLabel', background='#f5f5f5', font=('Segoe UI', 9))
        style.configure('TButton', font=('Segoe UI', 9), padding=6)
        style.configure('TEntry', font=('Segoe UI', 9), padding=5)
        style.configure('TLabelframe', background='#f5f5f5', font=('Segoe UI', 9))
        style.configure('TLabelframe.Label', background='#f5f5f5')

        # Custom button styles
        style.map('primary.TButton',
                  foreground=[('active', 'white'), ('!active', 'white')],
                  background=[('active', '#45a049'), ('!active', '#4CAF50')])
        style.map('danger.TButton',
                  foreground=[('active', 'white'), ('!active', 'white')],
                  background=[('active', '#d32f2f'), ('!active', '#f44336')])

        # ===== Main Layout =====
        main_frame = ttk.Frame(self.root, padding="10")
        main_frame.pack(fill=tk.BOTH, expand=True)

        # ===== Top Section: Input Controls =====
        control_frame = ttk.LabelFrame(main_frame, text="控制面板", padding=(15, 10))
        control_frame.pack(fill=tk.X, pady=(0, 10))

        # Account ID row
        account_frame = ttk.Frame(control_frame)
        account_frame.pack(fill=tk.X, pady=5)

        ttk.Label(account_frame, text="账号ID:").pack(side=tk.LEFT, padx=(0, 5))
        self.account_entry = ttk.Entry(account_frame, width=27)
        self.account_entry.pack(side=tk.LEFT, padx=5)

        # Adjustment Step row
        adjustment_frame = ttk.Frame(control_frame)
        adjustment_frame.pack(fill=tk.X, pady=5)

        ttk.Label(adjustment_frame, text="调整幅度:").pack(side=tk.LEFT, padx=(0, 5))
        self.adjustment_entry = ttk.Entry(adjustment_frame, width=25)
        self.adjustment_entry.insert(0, "0.1")  # 默认值
        self.adjustment_entry.pack(side=tk.LEFT, padx=5)

        # Add some spacing
        ttk.Frame(account_frame, width=20).pack(side=tk.LEFT)

        # File import row
        file_frame = ttk.Frame(control_frame)
        file_frame.pack(fill=tk.X, pady=5)

        self.btn_import = ttk.Button(file_frame, text="选择文件", command=self.import_excel)
        self.btn_import.pack(side=tk.LEFT)

        self.file_path_label = ttk.Label(
            file_frame,
            text="未选择文件",
            foreground="gray",
            wraplength=500,
            background='#f5f5f5'
        )
        self.file_path_label.pack(side=tk.LEFT, padx=10, expand=True, fill=tk.X)

        # Action buttons
        btn_frame = ttk.Frame(control_frame)
        btn_frame.pack(pady=10)

        self.btn_start = ttk.Button(
            btn_frame,
            text="▶ 开始执行",
            command=self.start_auto_bid,
            style='primary.TButton',
            state=tk.DISABLED
        )
        self.btn_start.pack(side=tk.LEFT, padx=5, ipadx=10)

        self.btn_stop = ttk.Button(
            btn_frame,
            text="■ 停止调整",
            command=self.stop_adjustment,
            style='danger.TButton',
            state=tk.DISABLED
        )
        self.btn_stop.pack(side=tk.LEFT, padx=5, ipadx=10)

        # ===== Log Sections using PanedWindow =====
        log_pane = ttk.PanedWindow(main_frame, orient=tk.VERTICAL)
        log_pane.pack(fill=tk.BOTH, expand=True, pady=5)

        # ----- Normal Log Area (90%) -----
        normal_log_frame = ttk.LabelFrame(log_pane, text="调整记录", padding=(15, 10))
        normal_log_frame.pack(fill=tk.BOTH, expand=True)

        self.log_result_text = tk.Text(
            normal_log_frame,
            wrap=tk.WORD,
            font=('Consolas', 9),
            bg='white',
            padx=10,
            pady=10
        )
        self.log_result_text.pack(fill=tk.BOTH, expand=True)
        self.log_result_text.config(state=tk.DISABLED)

        scrollbar_normal = ttk.Scrollbar(normal_log_frame, orient="vertical", command=self.log_result_text.yview)
        scrollbar_normal.pack(side=tk.RIGHT, fill=tk.Y)
        self.log_result_text.config(yscrollcommand=scrollbar_normal.set)

        log_pane.add(normal_log_frame, weight=90)  # 占比 90%

        # ----- Countdown Log Area (10%) -----
        countdown_log_frame = ttk.LabelFrame(log_pane, text="倒计时记录", padding=(15, 10))
        countdown_log_frame.pack(fill=tk.BOTH, expand=False)

        self.countdown_log_result_text = tk.Text(
            countdown_log_frame,
            wrap=tk.NONE,
            height=3,
            font=('Consolas', 9),
            bg='#f9f9f9',
            padx=5,
            pady=5
        )
        self.countdown_log_result_text.pack(fill=tk.BOTH, expand=False)
        self.countdown_log_result_text.config(state=tk.DISABLED)

        scrollbar_countdown = ttk.Scrollbar(countdown_log_frame, orient="vertical", command=self.countdown_log_result_text.yview)
        scrollbar_countdown.pack(side=tk.RIGHT, fill=tk.Y)
        self.countdown_log_result_text.config(yscrollcommand=scrollbar_countdown.set)

        log_pane.add(countdown_log_frame, weight=10)  # 占比 10%

        # ===== Status Bar =====
        status_bar = ttk.Frame(self.root, relief=tk.SUNKEN)
        status_bar.pack(fill=tk.X, pady=(5, 0))

        self.status_label = ttk.Label(status_bar, text="就绪", foreground="green")
        self.status_label.pack(side=tk.LEFT, padx=5)

        ttk.Label(status_bar, text="").pack(side=tk.RIGHT, padx=5)

    def import_excel(self):
        filepath = filedialog.askopenfilename(
            title="选择Excel文件",
            filetypes=[("Excel 文件", "*.xlsx *.xls"), ("所有文件", "*.*")]
        )
        if not filepath:
            return

        try:
            self.data = load_excel_data(filepath)
            log_message(self.log_result_text, f"✅ Excel数据加载完成, 共加载 {len(self.data)} 条数据")

            # Update file path display (show only filename if path is too long)
            filename = filepath.split('/')[-1] if '/' in filepath else filepath
            self.file_path_label.config(text=filename, foreground="black")

            # Enable "Start" button
            self.btn_start.config(state=tk.NORMAL)
            self.status_label.config(text="数据加载成功", foreground="green")

        except Exception as e:
            messagebox.showerror("错误", f"读取Excel失败:\n{str(e)}")
            self.status_label.config(text="数据加载失败", foreground="red")

    def start_auto_bid(self):
        # if self.adjustment_thread and self.adjustment_thread.is_alive():
        #     log_message(self.log_result_text, "调整程序已在运行中", "red")
        #     return

        account_id = self.account_entry.get().strip()
        adjustment_str = self.adjustment_entry.get().strip()

        if not account_id:
            log_message(self.log_result_text, "请输入账号ID！", "red")
            self.status_label.config(text="需要账号ID", foreground="red")
            return

        try:
            adjustment = float(adjustment_str)
        except ValueError:
            log_message(self.log_result_text, "⚠️ 调整幅度必须是数字，默认使用 0.1", "orange")
            adjustment = 0.1

        self.stop_event = threading.Event()
        self.adjustment_thread = threading.Thread(
            target=adjust_bids_periodically,
            args=(self.data, self.log_result_text, self.countdown_log_result_text, self.stop_event, account_id, adjustment)
        )
        self.adjustment_thread.daemon = True
        self.adjustment_thread.start()

        self.btn_start.config(state=tk.DISABLED)
        self.btn_stop.config(state=tk.NORMAL)
        self.btn_import.config(state=tk.DISABLED)
        self.status_label.config(text="自动调价运行中...", foreground="blue")
        log_message(self.log_result_text, "▶ 自动调价已启动")

    def stop_adjustment(self):
        if self.stop_event:
            self.stop_event.set()
        self.btn_import.config(state=tk.NORMAL)
        self.btn_stop.config(state=tk.DISABLED)
        self.btn_start.config(state=tk.NORMAL)
        self.status_label.config(text="已停止", foreground="orange")
        log_message(self.log_result_text, "■ 已手动停止自动调整")